/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[TestPriorityQueue.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package collections;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;

/**
 * 集合框架 - java.util.PriorityQueue
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TestPriorityQueue {

	/**
	 * 测试Integer元素类型的优先队列
	 */
	public static void testIntegerPriorityQueue() {
		// 优先队列自然排序示例
		Queue<Integer> integerPriorityQueue = new PriorityQueue<>(10);
		Random random = new Random();
		for (int i = 0; i < 10; i++) {
			integerPriorityQueue.add(new Integer(random.nextInt(100)));
		}
		for (int i = 0; i < 10; i++) {
			Integer in = integerPriorityQueue.poll();
			System.out.println("Processing Integer: " + in);
		}
	}

	/**
	 * 测试自定义元素类型的优先队列
	 */
	public static void testCustomerPriorityQueue() {
		// 优先队列使用示例
		Queue<Customer> customerPriorityQueue = new PriorityQueue<>(10, idComparator);
		addDataToQueue(customerPriorityQueue);
		pollDataFromQueue(customerPriorityQueue);
	}

	/**
	 * 匿名Comparator实现
	 */
	public static Comparator<Customer> idComparator = new Comparator<Customer>() {
		@Override
		public int compare(Customer customer1, Customer customer2) {
			return customer1.getId() - customer2.getId();
		}
	};

	/**
	 * 用于往队列增加数据的通用方法
	 * 
	 * @param customerPriorityQueue
	 */
	private static void addDataToQueue(Queue<Customer> customerPriorityQueue) {
		Random rand = new Random();
		for (int i = 0; i < 10; i++) {
			int id = rand.nextInt(100);
			customerPriorityQueue.add(new Customer(id, "Sean " + id));
		}
	}

	/**
	 * 用于从队列取数据的通用方法
	 * 
	 * @param customerPriorityQueue
	 */
	private static void pollDataFromQueue(Queue<Customer> customerPriorityQueue) {
		while (!customerPriorityQueue.isEmpty()) {
			Customer customer = customerPriorityQueue.poll();
			if (customer != null) {
				System.out.println("Processing Customer with ID = " + customer.getId());
			}
		}
	}

	public static void main(String[] args) {
		testIntegerPriorityQueue();
		testCustomerPriorityQueue();
	}
}

/**
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 *
 */
class Customer {

	private int id;
	private String name;

	public Customer(int i, String n) {
		this.id = i;
		this.name = n;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}
}
